package dongshi.daddy.huohuo;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.IntStream;

public class ReadWriteLockCounter {
    public static void main(String[] args) {
        int loopNum = 100_0090;
        ReadWriteLockCounter loopCounter = new ReadWriteLockCounter();
        IntStream.range(0, loopNum).parallel().forEach(i -> loopCounter.incrAndGet());
        System.out.println("sum 最终：" + loopCounter.getSum());
    }

    private int sum = 0;
    // 可重复 读写 公平锁
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);

    public int incrAndGet() {
        try {
            readWriteLock.writeLock().lock();
            return ++sum;
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public int getSum() {
        try {
            readWriteLock.readLock().lock();
            return sum;
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}
